﻿using System;
using System.Text;
using System.Drawing.Design;
using System.ComponentModel;
using System.Windows.Forms.Design;

namespace MyFastDataSourceBind
{
    /// <summary>
    /// 编辑数据源名称的扩展编辑器
    /// </summary>
    /// <remarks>编制 袁永福</remarks>
    public class XDataSourceNameEditor : UITypeEditor
    {
        /// <summary>
        /// 初始化对象
        /// </summary>
        public XDataSourceNameEditor()
        {
        }
        /// <summary>
        /// 返回编辑器使用样式为下拉列表样式
        /// </summary>
        /// <param name="context">参数</param>
        /// <returns>下拉列表样式</returns>
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            // 返回下拉列表样式
            return UITypeEditorEditStyle.DropDown;
        }
        /// <summary>
        /// 编辑数值
        /// </summary>
        /// <param name="context">参数</param>
        /// <param name="provider">参数</param>
        /// <param name="Value">旧数值</param>
        /// <returns>编辑后的新数值</returns>
        public override object EditValue(
            ITypeDescriptorContext context,
            IServiceProvider provider,
            object Value)
        {
            if (provider == null)
                return Value;
            // 获得服务对象
            IWindowsFormsEditorService svc =
                (IWindowsFormsEditorService)provider.GetService(
                typeof(IWindowsFormsEditorService));
            if (svc == null)
                return Value;

            using (DesignPopupListBox lst = new DesignPopupListBox())
            {
                foreach (XDataSource ds in XDataSource.GetInstances())
                {
                    // 遍历所有的全局数据源对象并将名称添加到列表控件中
                    lst.AddItem(ds.Name, ds.Description);
                }
                if (lst.Items.Count > 0)
                {
                    // 若有列表项目则弹出该列表控件
                    string v = lst.Popup(svc, Convert.ToString(Value));
                    if (v != null)
                    {
                        // 返回用户选择的数据源名称
                        return v;
                    }
                }
            }
            return Value;
        }//public override EditValue()

    }//public class XDataSourceUITypeEditor : UITypeEditor
}